<template>
  <div>
    <h1>字符不能直接写在template中</h1>
    <h2>template的子标签可以包含多个，但这里的描述可能指的是特定上下文（如某些库的限制），不过Vue的template本身没有这个限制。</h2>
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="账号" prop="username">
        <el-input v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPassword">
        <el-input type="password" v-model="ruleForm.checkPassword" autocomplete="off"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        username: '',
        password: '',
        checkPassword: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        checkPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: this.validatePassword, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    validatePassword(rule, value, callback) {
      if (value !== this.ruleForm.password) {
        callback(new Error('两次密码不一致'));
      } else {
        callback();
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const username = this.ruleForm.username;
          const password = this.ruleForm.password;
          if (username === 'admin' && password === '123456') {
            this.$message({
              message: '登录成功',
              type: 'success'
            });
          } else {
            this.$message({
              message: '账号或密码错误',
              type: 'error'
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>

<style>
/* 添加一些简单的样式 */
.demo-ruleForm .el-form-item {
  margin-bottom: 20px;
}
</style>
